package com.eddie.juc.locks;

import java.util.ArrayList;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Eddie
 * @date 2022/08/18 16:35
 **/
public class SaleTicketDemo {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(() -> {
            for (int i = 0; i < 55; i++) {
                ticket.sale();
            }
        }, "a").start();
        new Thread(() -> {
            for (int i = 0; i < 55; i++) {
                ticket.sale();
            }
        }, "b").start();
        new Thread(() -> {
            for (int i = 0; i < 55; i++) {
                ticket.sale();
            }
        }, "c").start();

    }
}

/**
 * 资源类，模拟三个售票员卖完50张票
 */
class Ticket {
    private int number = 50;
    /**
     * 可重入锁
     * 使用空参构造默认是非公平锁，使用true为公平锁
     */
    ReentrantLock lock = new ReentrantLock(true);

    public void sale() {
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出第：\t" + (number--) + "\t还剩下：" + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}

